import { post, apiPaths } from '../../utils/request.js'

Page({
  data: {
    taskId: null,
    projectId: null,
    action: null,
    task: {
      id: null,
      title: '',
      description: '',
      priority: '中',
      status: '待处理',
      assigneeId: null,
      assigneeName: '',
      projectName: '',
      creatorName: '',
      createdAt: '',
      updatedAt: ''
    },
    attachments: [],
    logs: [],
    priorityList: ['紧急', '高', '中', '低'],
    statusList: ['待处理', '处理中', '待测试', '已完成'],
    showActionSheet: false
  },

  onLoad(options) {
    if (options.action === 'create') {
      // 创建任务模式
      this.setData({
        action: 'create',
        projectId: options.projectId || null
      })
      wx.setNavigationBarTitle({
        title: '创建任务'
      })
    } else if (options.id) {
      // 编辑任务模式
      this.setData({
        taskId: options.id,
        action: 'edit'
      })
      this.loadTaskDetail(options.id)
      wx.setNavigationBarTitle({
        title: '任务详情'
      })
    }
  },

  loadTaskDetail(taskId) {
    // 调用获取任务详情接口
    post(apiPaths.getTaskDetail, { id: taskId }).then(res => {
      if (res.code === 200) {
        const data = res.data
        const task = {
          id: data.task.id,
          title: data.task.title,
          description: data.task.description,
          priority: data.task.priority,
          status: data.task.status,
          assigneeId: data.task.assignee_id,
          assigneeName: data.task.assignee_name,
          projectName: data.task.project_name,
          creatorName: data.task.creator_name,
          createdAt: data.task.created_at,
          updatedAt: data.task.updated_at
        }
        
        // 处理优先级类名
        let priorityClass = 'medium'
        if (task.priority === '紧急') {
          priorityClass = 'urgent'
        } else if (task.priority === '高') {
          priorityClass = 'high'
        } else if (task.priority === '中') {
          priorityClass = 'medium'
        } else if (task.priority === '低') {
          priorityClass = 'low'
        }
        
        // 处理状态类名
        let statusClass = 'default'
        if (task.status === '待处理') {
          statusClass = '待处理'
        } else if (task.status === '处理中') {
          statusClass = '处理中'
        } else if (task.status === '待测试') {
          statusClass = '待测试'
        } else if (task.status === '已完成') {
          statusClass = '已完成'
        }
        
        task.priorityClass = priorityClass
        task.statusClass = statusClass
        
        this.setData({
          task: task,
          attachments: data.attachments || [],
          logs: data.logs || []
        })
      } else {
        wx.showToast({
          title: res.message || '获取任务详情失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message || '获取任务详情失败',
        icon: 'none'
      })
    })
  },

  onTitleInput(e) {
    this.setData({
      'task.title': e.detail.value
    })
  },

  onDescriptionInput(e) {
    this.setData({
      'task.description': e.detail.value
    })
  },

  onChangePriority() {
    const priorityList = this.data.priorityList
    const currentPriorityIndex = priorityList.indexOf(this.data.task.priority)
    
    wx.showActionSheet({
      itemList: priorityList,
      itemColor: '#000',
      selectedItemColor: '#007AFF',
      defaultColor: '#000',
      selectedIndex: currentPriorityIndex,
      success: (res) => {
        if (!res.cancel) {
          const newPriority = priorityList[res.tapIndex]
          this.updateTaskPriority(newPriority)
        }
      }
    })
  },

  updateTaskPriority(newPriority) {
    post(apiPaths.updateTask, {
      id: this.data.taskId,
      priority: newPriority
    }).then(res => {
      if (res.code === 200) {
        // 更新本地数据
        let priorityClass = 'medium'
        if (newPriority === '紧急') {
          priorityClass = 'urgent'
        } else if (newPriority === '高') {
          priorityClass = 'high'
        } else if (newPriority === '中') {
          priorityClass = 'medium'
        } else if (newPriority === '低') {
          priorityClass = 'low'
        }
        
        this.setData({
          'task.priority': newPriority,
          'task.priorityClass': priorityClass
        })
        
        wx.showToast({
          title: '优先级更新成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: res.message || '优先级更新失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message || '优先级更新失败',
        icon: 'none'
      })
    })
  },

  onEditTask() {
    console.log('编辑任务按钮被点击')
    // 跳转到编辑任务页面
    wx.navigateTo({
      url: '/pages/createTask/createTask?taskId=' + this.data.taskId + '&action=edit'
    })
  },

  onViewLogs() {
    console.log('查看日志按钮被点击')
    // 跳转到任务日志页面
    wx.navigateTo({
      url: '/pages/taskLogs/taskLogs?taskId=' + this.data.taskId
    })
  },

  onOpenChat() {
    console.log('打开群聊按钮被点击')
    // 跳转到任务群聊页面
    wx.navigateTo({
      url: '/pages/taskChat/taskChat?taskId=' + this.data.taskId
    })
  },

  onShowMoreActions() {
    console.log('更多操作按钮被点击')
    wx.showActionSheet({
      itemList: ['编辑任务', '删除任务'],
      itemColor: '#000',
      selectedItemColor: '#FF3B30',
      defaultColor: '#000',
      success: (res) => {
        if (!res.cancel) {
          if (res.tapIndex === 0) {
            // 编辑任务
            this.onEditTask()
          } else if (res.tapIndex === 1) {
            // 删除任务
            this.onDeleteTask()
          }
        }
      }
    })
  },

  onAddAttachment() {
    // 选择文件
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].path
        const fileName = res.tempFiles[0].name
        
        // 上传文件
        wx.uploadFile({
          url: 'http://175.178.156.176:8092/task' + apiPaths.uploadTaskAttachment,
          filePath: tempFilePath,
          name: 'file',
          formData: {
            taskId: this.data.taskId,
            fileName: fileName
          },
          header: {
            'Authorization': wx.getStorageSync('token')
          },
          success: (uploadRes) => {
            const data = JSON.parse(uploadRes.data)
            if (data.code === 200) {
              wx.showToast({
                title: '附件上传成功',
                icon: 'success'
              })
              // 重新加载任务详情
              this.loadTaskDetail(this.data.taskId)
            } else {
              wx.showToast({
                title: data.message || '附件上传失败',
                icon: 'none'
              })
            }
          },
          fail: (err) => {
            wx.showToast({
              title: '附件上传失败',
              icon: 'none'
            })
          }
        })
      },
      fail: (err) => {
        wx.showToast({
          title: '选择文件失败',
          icon: 'none'
        })
      }
    })
  },

  onDeleteAttachment(e) {
    const attachmentId = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认删除',
      content: '确定要删除该附件吗？',
      success: (res) => {
        if (res.confirm) {
          // 调用删除附件接口
          post(apiPaths.deleteTaskAttachment, {
            id: attachmentId
          }).then(res => {
            if (res.code === 200) {
              wx.showToast({
                title: '附件已删除',
                icon: 'success'
              })
              // 重新加载任务详情
              this.loadTaskDetail(this.data.taskId)
            } else {
              wx.showToast({
                title: res.message || '附件删除失败',
                icon: 'none'
              })
            }
          }).catch(err => {
            wx.showToast({
              title: err.message || '附件删除失败',
              icon: 'none'
            })
          })
        }
      }
    })
  },

  onAddLog() {
    // 显示输入框让用户输入日志内容
    wx.showModal({
      title: '添加日志',
      editable: true,
      placeholderText: '请输入日志内容',
      success: (res) => {
        if (res.confirm) {
          const content = res.content
          if (content) {
            const userInfo = wx.getStorageSync('userInfo') || {}
            const userId = userInfo.id
            
            if (!userId) {
              wx.showToast({
                title: '用户信息错误',
                icon: 'none'
              })
              return
            }
            
            if (!this.data.taskId) {
              wx.showToast({
                title: '任务ID不能为空',
                icon: 'none'
              })
              return
            }
            
            // 调用添加日志接口
            post(apiPaths.addTaskLog, {
              taskId: this.data.taskId,
              userId: userId,
              action: '添加日志',
              description: content
            }).then(res => {
              if (res.code === 200) {
                wx.showToast({
                  title: '日志添加成功',
                  icon: 'success'
                })
                // 重新加载任务详情
                this.loadTaskDetail(this.data.taskId)
              } else {
                wx.showToast({
                  title: res.message || '日志添加失败',
                  icon: 'none'
                })
              }
            }).catch(err => {
              wx.showToast({
                title: err.message || '日志添加失败',
                icon: 'none'
              })
            })
          }
        }
      }
    })
  },

  onDeleteTask() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除该任务吗？此操作不可恢复',
      success: (res) => {
        if (res.confirm) {
          // 调用删除任务接口
          post(apiPaths.deleteTask, {
            id: this.data.taskId
          }).then(res => {
            if (res.code === 200) {
              wx.showToast({
                title: '任务已删除',
                icon: 'success'
              })
              setTimeout(() => {
                wx.navigateBack()
              }, 1500)
            } else {
              wx.showToast({
                title: res.message || '任务删除失败',
                icon: 'none'
              })
            }
          }).catch(err => {
            wx.showToast({
              title: err.message || '任务删除失败',
              icon: 'none'
            })
          })
        }
      }
    })
  }
})